package org.xmx0632.connector.util.client;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Handles a client-side channel.
 */
@Sharable
public class TcpClientHandler extends SimpleChannelInboundHandler<String> {

	private int maxCounter = 2;
	private long sendInterval = 1;
	
	private int currCounter = 0;

	public TcpClientHandler(int sendInterval , int maxCounter ) {
		this.sendInterval = sendInterval;
		this.maxCounter = maxCounter;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

		String[] testContent1 = { "register" };
		String[] testContent2 = {  "heartbeat", "heartbeat" };
		int length = testContent2.length;

		int counter = 0;
		int index = 0;
		while (true) {
			if (counter >= maxCounter ) {
				break;
			}
			String line = "";
			counter++;
			if(counter ==1){
				line = testContent1[0];
			}else{
				index = counter  % length;
				line = testContent2[index];
			}
			String command = CommandUtil.getCommand(line,counter);
			ChannelFuture f = ctx.writeAndFlush(command + "\r\n");
			f.addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					System.out.println("===========write message success==========" + maxCounter + " reach max:" + currCounter);
					currCounter++;
					if(currCounter>= maxCounter){
						System.out.println(maxCounter + " reach max:" + currCounter);
//						future.channel().close();
					}
				}
			});
			Thread.sleep(sendInterval );
		}
		System.out.println("test finish");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.err.println("exception!!! close connection now.");
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println("response:" + msg);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		System.err.println("channelInactive!!! close connection now.");
		System.exit(0);
	}

}
